import React, { useRef, useEffect } from 'react';
import { useAudioStore, toggleAudio } from '@/lib/audioManager';
import { useTranslatorStore } from '@/store/translator';
import AudioButton from '../common/AudioButton';
import { textToSpeech } from '@/lib/speech';

interface TranslationResultProps {
  fontSize: 'small' | 'medium' | 'large';
  isSpeakerOn: boolean;
}

const TranslationResult: React.FC<TranslationResultProps> = ({
  fontSize,
  isSpeakerOn,
}) => {
  const { translations, isLoading } = useTranslatorStore();
  const { isPlaying, audio } = useAudioStore();
  const [currentPlayingId, setCurrentPlayingId] = React.useState<string | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [translations]);

  useEffect(() => {
    if (!isPlaying) {
      setCurrentPlayingId(null);
    }
  }, [isPlaying]);

  const getFontSize = (size: 'small' | 'medium' | 'large') => {
    switch (size) {
      case 'small': return 'text-sm';
      case 'medium': return 'text-base';
      case 'large': return 'text-lg';
      default: return 'text-base';
    }
  };

  const handleSpeak = async (text: string, id: string, isSource: boolean) => {
    try {
      if (currentPlayingId === id && isPlaying) {
        await toggleAudio();
      } else {
        setCurrentPlayingId(id);
        await textToSpeech(text, isSource ? 'zh' : 'en');
      }
    } catch (error) {
      console.error('Speech error:', error);
      setCurrentPlayingId(null);
    }
  };

  return (
    <div className="h-full overflow-y-auto" ref={scrollRef}>
      <div className="max-w-2xl mx-auto p-6 space-y-6">
        {translations.map((translation) => (
          <div key={translation.id} className="space-y-3">
            {/* Source Text */}
            <div className="flex items-start space-x-3">
              <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-green-600">原</span>
              </div>
              <div className="flex-1 max-w-lg">
                <div className="bg-blue-50/80 backdrop-blur-sm rounded-lg p-4 shadow-sm border border-blue-100/50">
                  <div className="flex justify-between items-start">
                    <p className={`${getFontSize(fontSize)} text-gray-800 leading-relaxed flex-1`}>
                      {translation.sourceText}
                    </p>
                    <AudioButton
                      onClick={() => handleSpeak(translation.sourceText, `${translation.id}-source`, true)}
                      isEnabled={isSpeakerOn}
                      isCurrentlyPlaying={currentPlayingId === `${translation.id}-source`}
                      variant="primary"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Translation Result */}
            <div className="flex items-start space-x-3 pl-11">
              <div className="flex-1 max-w-lg">
                <div className="bg-green-50/80 backdrop-blur-sm rounded-lg p-4 shadow-sm border border-green-100/50">
                  <div className="flex justify-between items-start">
                    <p className={`${getFontSize(fontSize)} text-green-700 leading-relaxed flex-1`}>
                      {translation.translatedText}
                    </p>
                    <AudioButton
                      onClick={() => handleSpeak(translation.translatedText, `${translation.id}-target`, false)}
                      isEnabled={isSpeakerOn}
                      isCurrentlyPlaying={currentPlayingId === `${translation.id}-target`}
                      variant="secondary"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        ))}

        {/* Loading State */}
        {isLoading && (
          <div className="flex items-center justify-center py-4">
            <div className="animate-pulse text-gray-500">正在翻译...</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default TranslationResult;